/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CadSubCategoria.java
 *
 * Created on 17/11/2011, 16:36:59
 */
package visao;

import categoria.Categoria;
import categoria.CategoriaNaoCadastradoException;
import fachada.FachadaBDR;
import java.awt.Color;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import subCategoria.SubCategoria;
import subCategoria.SubCategoriaNaoCadastradoException;
import util.CamposObrigatoriosException;
import util.ErroAcessoRepositorioException;
import util.KeyValue;

/**
 *
 * @author Administrador
 */
public class CadSubCategoria extends javax.swing.JFrame {

    /** Creates new form CadSubCategoria */
    public CadSubCategoria() {
        initComponents();

        this.setLocationRelativeTo(null);
        this.setIconImage(new ImageIcon(getClass().getResource("/Imagens/visao.gif")).getImage());
    }

    /** Creates new form CadSubCategoria */
    public CadSubCategoria(int idSubCategoria) {
        initComponents();
        this.setLocationRelativeTo(null);
        this.setIconImage(new ImageIcon(getClass().getResource("/Imagens/visao.gif")).getImage());

        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
            // recuperando a subcategoria 
            SubCategoria objSubCategoria = objFachadaBDR.procurarSubCategoria(idSubCategoria);
            // recuperando os objetos associados
            Categoria objCategoria = objSubCategoria.getCategoria();

            id_sub_categoria.setText(String.valueOf(objSubCategoria.getIdSubCategoria()));
            jComboBox_IdCategoria.setSelectedItem(new KeyValue(objCategoria.getNome(), Integer.toString(objCategoria.getIdCategoria())));
            jTextField_Descricao.setText(objSubCategoria.getNome());
            jCheckBox_Status.setSelected(objSubCategoria.getStatusSubCategoria());

        } catch (SubCategoriaNaoCadastradoException ex) {
            Logger.getLogger(CadSubCategoria.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ErroAcessoRepositorioException ex) {
            Logger.getLogger(CadSubCategoria.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToggleButton1 = new javax.swing.JToggleButton();
        jLabel_Codigo = new javax.swing.JLabel();
        jLabel_Descricao = new javax.swing.JLabel();
        jLabel_Categoria = new javax.swing.JLabel();
        jTextField_Descricao = new javax.swing.JTextField();
        jComboBox_IdCategoria = new javax.swing.JComboBox();
        jCheckBox_Status = new javax.swing.JCheckBox();
        jButton_Ok = new javax.swing.JButton();
        jButton_Cancelar = new javax.swing.JButton();
        jLabel_Mensagem = new javax.swing.JLabel();
        id_sub_categoria = new javax.swing.JTextField();

        jToggleButton1.setText("jToggleButton1");

        setTitle("SubCategoria");
        setResizable(false);

        jLabel_Codigo.setText("Codigo :");

        jLabel_Descricao.setText("Descrição :");

        jLabel_Categoria.setText("Categoria :");

        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

            List<Categoria> listCategoria = objFachadaBDR.listarCategoria("");

            jComboBox_IdCategoria.addItem(new KeyValue("--- Favor Selecionar ---","0"));
            for (Categoria objCat : listCategoria) {
                jComboBox_IdCategoria.addItem(new KeyValue(objCat.getNome(), Integer.toString(objCat.getIdCategoria())));
            }

        } catch (Exception e) {
        }

        jCheckBox_Status.setSelected(true);
        jCheckBox_Status.setText("Ativo");

        jButton_Ok.setText("Ok");
        jButton_Ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_OkActionPerformed(evt);
            }
        });

        jButton_Cancelar.setText("Cancelar");
        jButton_Cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_CancelarActionPerformed(evt);
            }
        });

        id_sub_categoria.setText("0");
        id_sub_categoria.setEnabled(false);
        id_sub_categoria.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                id_sub_categoriaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jButton_Ok, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton_Cancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel_Mensagem, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel_Codigo, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel_Descricao, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel_Categoria, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextField_Descricao, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(id_sub_categoria, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 150, Short.MAX_VALUE)
                                .addComponent(jCheckBox_Status)
                                .addGap(26, 26, 26))
                            .addComponent(jComboBox_IdCategoria, 0, 361, Short.MAX_VALUE))))
                .addGap(57, 57, 57))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(35, 35, 35)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel_Codigo)
                            .addComponent(id_sub_categoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(15, 15, 15)
                        .addComponent(jCheckBox_Status)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel_Descricao)
                    .addComponent(jTextField_Descricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel_Categoria)
                    .addComponent(jComboBox_IdCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_Ok)
                    .addComponent(jButton_Cancelar)
                    .addComponent(jLabel_Mensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_CancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CancelarActionPerformed
        // TODO add your handling code here:

        int cancelar = JOptionPane.showConfirmDialog(null, "Deseja cancelar ?");

        if (cancelar == JOptionPane.YES_OPTION) {

            dispose();

        } else {
        }


    }//GEN-LAST:event_jButton_CancelarActionPerformed

    private void jButton_OkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_OkActionPerformed
        // TODO add your handling code here:


        int idSubCategoria = Integer.parseInt(id_sub_categoria.getText());
        String descricao = jTextField_Descricao.getText();
        Boolean status = jCheckBox_Status.isSelected();
        int idCategoria = Integer.parseInt(((KeyValue) jComboBox_IdCategoria.getSelectedItem()).getValue());


        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

            Categoria categoria = objFachadaBDR.procurarCategoria(idCategoria);

            SubCategoria subcategoria = new SubCategoria(idSubCategoria, categoria, descricao, status, null);

            if (idSubCategoria == 0) {
                objFachadaBDR.cadastrarSubCategoria(subcategoria);

                jComboBox_IdCategoria.setSelectedIndex(0);
                jTextField_Descricao.setText("");
                jCheckBox_Status.setSelected(false);

            } else {
                objFachadaBDR.atualizarSubCategoria(subcategoria);
            }

            String acao = (idSubCategoria == 0) ? "inserida" : "atualizada";
            jLabel_Mensagem.setText("SubCategoria " + acao + " com sucesso.");
            jLabel_Mensagem.setForeground(Color.BLACK);


        } catch (CategoriaNaoCadastradoException ex) {
            Logger.getLogger(CadSubCategoria.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CamposObrigatoriosException ex) {
            Logger.getLogger(CadSubCategoria.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ErroAcessoRepositorioException ex) {
            Logger.getLogger(CadSubCategoria.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_jButton_OkActionPerformed

    private void id_sub_categoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_id_sub_categoriaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_id_sub_categoriaActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new CadSubCategoria().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField id_sub_categoria;
    private javax.swing.JButton jButton_Cancelar;
    private javax.swing.JButton jButton_Ok;
    private javax.swing.JCheckBox jCheckBox_Status;
    private javax.swing.JComboBox jComboBox_IdCategoria;
    private javax.swing.JLabel jLabel_Categoria;
    private javax.swing.JLabel jLabel_Codigo;
    private javax.swing.JLabel jLabel_Descricao;
    private javax.swing.JLabel jLabel_Mensagem;
    private javax.swing.JTextField jTextField_Descricao;
    private javax.swing.JToggleButton jToggleButton1;
    // End of variables declaration//GEN-END:variables
}
